package com.wf.DouDiZhuOL.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import com.wf.DouDiZhuOL.MainFrame;

public class Config {
	public static String SERVER_CONFIG_PATH = "/server.properties"; // 服务器的配置路径
	
	private Map<String, Properties> propertiesMap;
	
	private static Config _instance = null;
	
	public static Config getInstance() 
	{
		if(_instance == null) 
		{
			_instance = new Config();
			_instance.init();
		}
		return _instance;
	}
	
	private void init() 
	{
		propertiesMap = new HashMap<String, Properties>();
	}
	
	public void loadAllConfig() 
	{
		this.loadConfig(SERVER_CONFIG_PATH);
	}
	
	private void loadConfig(String _file) 
	{
		Properties properties = new Properties();
		
		InputStream is = Config.class.getResourceAsStream(_file);
		try {
			if(is != null) 
			{
				properties.load(is);
				propertiesMap.put(_file, properties);
				this.printConfig(properties, _file);
			}else 
			{
				MainFrame.setText("没有找到配置文件：" + _file);
			}
		}
		catch (IOException e) 
		{
			e.printStackTrace();
			MainFrame.setText("加载配置文件错误");
		}
		finally 
		{
			try 
			{
				if(is != null) 
				{
					is.close();
				}
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	public String get(String _file, String _key) 
	{
		Properties properties = propertiesMap.get(_file);
		
		if(properties == null || properties.size() == 0) 
		{
			loadConfig(_file);
		}
		
		String ret = properties.getProperty(_key);
		if(ret != null)
		{
			return ret.trim();
		}
		return null;
	}
	
	public String get(String _file, String _key, String _default) 
	{
		String ret = this.get(_file, _key);
		if(ret == null)
		{
			return _default;
		}
		return ret;
	}
	
	public int get(String _file, String _key, int _default) 
	{
		String ret = this.get(_file, _key);
		if(ret == null)
		{
			return _default;
		}
		return Integer.parseInt(ret);
	}
	
	private void printConfig(Properties _properties, String _file) 
	{
		MainFrame.setText("===================" + _file + " Conf ==========================");
		Set<Entry<Object, Object>> entrySet = _properties.entrySet();
		for (Entry<Object, Object> entry : entrySet) {
			MainFrame.setText("server conf:"+ entry.getKey() + "->" + entry.getValue());
		}
		MainFrame.setText("===================" + _file + " Conf==========================");
	}
}
